<template>
  <el-dropdown v-bind="$attrs">
    <slot></slot>
    <template #dropdown>
      <el-dropdown-menu v-for="(item, index) in options" :key="index">
        <el-dropdown-item
          v-bind="item"
          :icon="handleIcon(item)"
          :class="{
            active: active && active === item.command,
            hiddenIcon: activeIcon ? active !== item.command : false,
            same: activeIcon,
          }"
        >
          {{ item.label }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import { useDiscMinSvg } from '@/hooks/index'
import { Component, PropType } from 'vue'
import { Options } from './type.ts'
defineOptions({
  name: 'XuDropdown',
})
defineProps({
  options: {
    type: Array as PropType<Options[]>,
    defalut: [],
  },
  active: {
    type: [String, Number, Object],
  },
  /**
   * 只显示active的图标
   */
  activeIcon: {
    type: Boolean,
    default: false,
  },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isComponent(obj: any): obj is Component {
  return obj && typeof obj.render === 'function'
}
const handleIcon = (item: Options) => {
  if (typeof item.icon === 'string') {
    return useDiscMinSvg(item.icon).component
  } else if (isComponent(item.icon)) {
    return item.icon
  }
}
</script>
<!-- 加scoped没有用，得在template中加一个根dom节点才有用 -->
<style lang="scss" scoped>
.el-dropdown-menu {
  padding: 0;

  :deep(.el-dropdown-menu__item) {
    color: var(--el-text-color-regular);

    &.is-disabled {
      color: var(--el-text-color-disabled);
    }

    &:not(.is-disabled):focus {
      // 防止覆盖掉选中的背景色
      background-color: initial;
    }

    &:not(.is-disabled):hover {
      background-color: var(--el-dropdown-menuItem-hover-fill);
    }
  }

  :deep(.active) {
    color: #fff;
    background-color: var(--el-color-primary) !important;
  }

  :deep(.hiddenIcon) {
    .el-icon {
      visibility: hidden;
    }
  }

  :deep(.same) {
    // 只有activeIcon的时候，右padding才会比左padding多一点
    padding-right: 35px;
  }
}
</style>
